<?php


namespace app\home\controller;

use app\home\model\Comment;
use app\home\model\Construction as ConstructionModel;
/**
 * Class Construction
 * @package app\home\controller
 * 党群建设
 */
class Construction extends Base
{
    public function _initialize()
    {
        parent::_initialize();
        $this->anonymous();
        $this->jssdk();
        $this->userid = session('userId');
    }

    /**
     *  党群建设首页
     */
    public function index () {
        $Model = new ConstructionModel();
        $uid = $this->userid;
        $length = input('length',0);
        if(IS_POST) {
            $type = input('type');
            $list = $Model->getList($uid,$type,$length);
            if($list) {
                return $this->success("加载成功","",$list);
            }else {
                return $this->error("加载失败");
            }
        }else {
            $list = [
                'type1' => $Model->getList($uid,1),
                'type2' => $Model->getList($uid,2),
                'type3' => $Model->getList($uid,3),
            ];
            $this->assign('list',json_encode($list));
            $this->assign('userid',$uid);
            return $this->fetch();
        }
    }

    /**
     *  党群建设发布
     */
    public function send () {
        if(IS_POST) {
            $data = input('post.');

            if(!empty($data['images'])){
                $data['images'] = json_encode($data['images']);
            }
            $data['uid'] = session('userId');
            $Model = new ConstructionModel();
            $info = $Model->save($data);

            if ($info) {
                return $this->success("发布成功", Url('Construction/index'));
            } else {
                return $this->error("发布失败", Url('Construction/send'));
            }
        }else {
            return $this->fetch();
        }
    }

    /**
     * 党群建设删除
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del() {
        if(IS_POST) {
            $id = input('id');
            $data['status'] = -1;
            $res = ConstructionModel::where('id',$id)->update($data);
            if($res) {
                $map = [
                    'table' => 'construction',
                    'aid' => $id
                ];
                Comment::where($map)->delete();
                return $this->success("删除成功", Url('Construction/index'));
            }else {
                return $this->error("删除失败");
            }
        }
    }

}
